<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j page-member-center">
    <!-- 头部 -->
    <MemberHeader />
    <!-- /头部 -->
    <div class="content buy-member">
      <div class="tit">
        <div class="tit-bg" />
        <div class="text">
          {{ $t('memberCenter.currentGrowthValue') }}：
          <span class="number">{{ memberInfo.growth }}</span>
        </div>
        <div class="tit-bg tit-r" />
        <!-- 会员等级 -->
      </div>
      <!-- 会员等级 -->
      <div class="item-box">
        <div
          v-for="(item, index) in userLevels"
          :key="index"
          class="item"
        >
          <div class="bg">
            <ImgShow :src="item.img" />
          </div>
          <div class="text-box">
            <div class="level">
              {{ item.levelName }}
            </div>
            <!-- 期数类型 1:日 2:周 3:月 4:季 5:年 -->
            <div class="time">
              {{ $t('memberCenter.shoppingMall') }}：{{ item.term }}
              {{ ['', $t('dayRi'), $t('week'), $t('month'), $t('season'), $t('year')][item.termType] }}
            </div>
            <div class="price">
              ￥
              <span class="big">{{ item.needAmount }}</span>
            </div>
            <div class="btn-box">
              <div class="limit">
                {{ $t('memberCenter.memberGrowthValue') }} ≥ {{ item.needGrowth }}
                {{ $t('memberCenter.availablePurchase') }}
              </div>
              <div
                class="btn"
                :class="(memberInfo.growth < item.needGrowth) ? 'default' : ''"
                @click="buyNow(item, index)"
              >
                {{ $t('buyNow') }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- /会员等级 -->
    </div>
    <!-- 支付弹窗 -->
    <div
      v-if="isShowPop"
      class="popup-mask"
    />
    <div
      v-if="isPayPop"
      class="popup-box"
    >
      <div class="tit">
        <div class="text">
          {{ $t('memberCenter.purchaseMembership') }}
        </div>
        <div
          class="close"
          @click="closePop"
        />
      </div>
      <div class="con">
        <div class="pay-number">
          <div class="text">
            {{ $t('memberCenter.openingTips1') }}
          </div>
          <div class="number">
            {{ userLevels[curIndex].levelName }}
          </div>
          <div class="text">
            {{ $t('memberCenter.openingTips2') }}
          </div>
          <div class="number">
            {{ userLevels[curIndex].needAmount }}
          </div>
          <div class="text">
            {{ $t('memberCenter.yuan') }}
          </div>
        </div>
        <div class="pay-way">
          <div
            v-if="paySwitchInfo.aliPaySwitch"
            class="item"
            @click="choosePayWay(PayTypeConstant.ALIPAY)"
          >
            <img
              src="@/assets/images/payment-aliPay.png"
              alt
            >
            <span class="payment-text">{{ $t('payment.aliPay') }}</span>
          </div>
          <div
            v-if="payHtml"
            v-rich="payHtml"
          />
          <div
            v-if="paySwitchInfo.wxPaySwitch"
            class="item"
            @click="choosePayWay(PayTypeConstant.WECHATPAY_SWEEP_CODE)"
          >
            <img
              src="@/assets/images/payment-wechatPay.png"
              alt
            >
            <span class="payment-text">{{ $t('payment.wechatPay') }}</span>
          </div>
          <div
            v-if="paySettlementType !== 1 && paySwitchInfo.payPalSwitch"
            class="item paypal"
            @click="choosePayWay(PayTypeConstant.PAYPAL)"
          >
            <img
              class="paypal-logo"
              src="@/assets/images/paypal.png"
              alt
            >
            <img
              class="paypal-text"
              src="@/assets/images/paypal-text.png"
              alt
            >
          </div>
          <div
            v-if="paySwitchInfo.balancePaySwitch"
            class="item"
            @click="choosePayWay(PayTypeConstant.BALANCEPAY)"
          >
            <img
              class="item-balance-img"
              src="@/assets/images/balancePay.png"
              alt
            >
            <span class="item-balance-span">
              {{ $t("payment.balancePay") }}
            </span>
          </div>
        </div>
      </div>
    </div>
    <!-- /支付弹窗 -->
    <!-- 微信支付弹窗 -->
    <div
      v-if="isWxPop"
      class="popup-box"
    >
      <div class="tit">
        <div class="text">
          {{ $t('memberCenter.weChatPayment') }}
        </div>
        <div
          class="close"
          @click="closePop"
        />
      </div>
      <div class="con">
        <div class="weixin-pay-code">
          <div class="text">
            {{ $t('memberCenter.weChatSweepPayment') }}
          </div>
          <div class="qrcode">
            <canvas id="wxPayQrCode" />
          </div>
          <div class="btn-box">
            <a
              href="javascript:void(0)"
              class="btn"
              @click="paySuccess"
            >{{ $t('memberCenter.completedPayment') }}</a>
            <a
              href="javascript:void(0)"
              class="btn gray"
              @click="closePop"
            >{{ $t('memberCenter.cancel') }}</a>
          </div>
        </div>
      </div>
    </div>
    <!-- /微信支付弹窗 -->

    <!-- 通联支付弹窗 -->
    <div
      v-if="isAllinpayPop"
      class="popup-box"
    >
      <div class="tit">
        <div class="text">
          {{ allinpayType === 'WeChat'?$t('memberCenter.weChatPayment'):$t('allinpay.aliPay') }}
        </div>
        <div
          class="close"
          @click="closePop"
        />
      </div>
      <div class="con">
        <div class="weixin-pay-code">
          <div class="text">
            {{ allinpayType === 'WeChat'?$t('memberCenter.weChatSweepPayment'):$t('allinpay.aliPaySweepPayment') }}
          </div>
          <div class="qrcode">
            <canvas id="allinpayQrCode" />
          </div>
          <div class="btn-box">
            <a
              href="javascript:void(0)"
              class="btn"
              @click="paySuccess"
            >{{ $t('memberCenter.completedPayment') }}</a>
            <a
              href="javascript:void(0)"
              class="btn gray"
              @click="closePop"
            >{{ $t('cancel') }}</a>
          </div>
        </div>
      </div>
    </div>
    <!-- /通联支付弹窗 -->
  </div>
</template>

<script setup>
import { loadTransition } from '@/utils/load-transition'
import Cookie from 'vue-cookies'
import MemberHeader from '@/components/member-header/index.vue'
import { PayType } from '@/utils/constant'
import QRCode from 'qrcode'
import { ElLoading, ElMessageBox, ElMessage } from 'element-plus'
import { checkPayWay } from '@/utils/index'
loadTransition()
const PayTypeConstant = ref(PayType) // 支付类型常量
const router = useRouter()
const memberInfo = ref({}) // 会员等级信息
const userLevels = ref([]) // 付费会员等级列表

const paySettlementType = ref(0) // 是否为通联支付 1：通联支付 0：非通联支付
const isAllinpayPop = ref(false)// 通联支付弹窗
const allinpayType = ref('WeChat') // 通联支付类型
let allinpayMemberInfo = null // 通联会员信息

onMounted(() => {
  // 未登录跳转到登录页
  if (!Cookie.get('bbcToken')) {
    router.replace({ path: '/login' })
  }

  paySettlementType.value = localStorage.getItem('bbcPaySettlementType') ? JSON.parse(localStorage.getItem('bbcPaySettlementType')).paySettlementType : 0
  if (paySettlementType.value === 1) {
    getAllinpayMember()
  }
  // 设置网页标题
  document.title = $t('memberCenter.purchaseMembership')
  // 获取会员等级信息
  http.get('/p/score/scoreLevel/page?levelType=' + 0).then(({ data }) => {
    memberInfo.value = data
  })

  // 获取付费会员等级列表
  http.get('/p/score/scoreLevel/page?levelType=' + 1).then(({ data }) => {
    getVipInternationalization(data.userLevels)
    userLevels.value = data.userLevels
  })

  getBalanceInfo()
  setDefaultPayType()
})

// 获取通联支付用户信息
const getAllinpayMember = () => {
  http({
    url: '/p/userExtension/getInfo',
    method: 'get'
  }).then(({ data }) => {
    allinpayMemberInfo = data
  })
}

// 立即购买
const curIndex = ref(0) // 当前套餐
const isPayPop = ref(false) // 是否显示支付方式弹窗
const currentBalance = ref(0) // 余额
const isShowPop = ref(false) // 是否显示弹窗
let memberLevelId = null // 当前会员等级id
const buyNow = (item, index) => {
  if (memberInfo.value.growth >= item.needGrowth) {
    if (!checkPayWay(paySwitchInfo.value)) return
    isShowPop.value = true
    isPayPop.value = true
    curIndex.value = index
    memberLevelId = item.id
  }
}
// 请求余额数据
const getBalanceInfo = () => {
  http.get('/p/userBalance/getBalanceInfo').then(({ data }) => {
    currentBalance.value = data
  })
}

/**
 * 设置默认支付类型
 */
const paySwitchInfo = ref('') // 支付类型
const setDefaultPayType = () => {
  http.get('/sys/config/info/getSysPaySwitch').then(({ data }) => {
    paySwitchInfo.value = data
  })
}
// 选择支付方式
const isWxPop = ref(false) // 是否微信支付弹窗
const payHtml = ref('') // 支付宝支付页面
const choosePayWay = (type) => {
  if (paySettlementType.value === 1) {
    // 余额支付前，判断是否开通余额支付
    if (getTip(type)) {
      return
    }
  }
  if (type === PayType.ALIPAY) {
    // 支付宝部分
    http.post('/p/level/payLevel', {
      id: memberLevelId,
      payType: type,
      returnUrl: window.location.origin + '/member-center',
      systemType: paySettlementType.value === 1 ? 2 : undefined
    }).then(({ data }) => {
      if (paySettlementType.value === 1) {
        // 通联支付需要生成二维码供用户扫码支付
        isAllinpayPop.value = true // 打开通联支付弹窗
        isPayPop.value = false // 关闭选择支付方式弹窗
        allinpayType.value = 'Alipay' // 设置通联支付类型为支付宝
        nextTick(() => {
          QRCode.toCanvas(document.getElementById('allinpayQrCode'), data.payInfo, { version: 6, errorCorrectionLevel: 'L' })
        })
        return
      }
      payHtml.value = data
      nextTick(() => {
        document.forms[0].submit()
      })
    })
  } else if (type === PayType.WECHATPAY_SWEEP_CODE) {
    // 微信部分
    http.post('/p/level/payLevel', {
      id: memberLevelId,
      payType: type,
      systemType: paySettlementType.value === 1 ? 2 : undefined,
      validateType: paySettlementType.value === 1 ? 0 : undefined
    }).then(({ data }) => {
      if (paySettlementType.value === 1) {
        // 通联支付需要生成二维码供用户扫码支付
        isAllinpayPop.value = true // 打开通联支付弹窗
        isPayPop.value = false // 关闭选择支付方式弹窗
        allinpayType.value = 'WeChat' // 设置通联支付类型为微信
        nextTick(() => {
          QRCode.toCanvas(document.getElementById('allinpayQrCode'), data.payInfo, { version: 6, errorCorrectionLevel: 'L' })
        })
        return
      }
      isWxPop.value = true
      isPayPop.value = false
      nextTick(function () {
        QRCode.toCanvas(document.getElementById('wxPayQrCode'), data, { version: 6, errorCorrectionLevel: 'L' })
      })
    })
  } else if (type === PayType.PAYPAL) {
    // PayPal部分
    const loading = ElLoading.service({
      lock: true,
      text: $t('loading'),
      background: 'rgba(255, 255, 255, 0.8)'
    })
    http.post('/p/level/payLevel', {
      id: memberLevelId,
      payType: type
    }).then(({ data }) => {
      window.location.href = data
    }).catch(() => {
      setTimeout(() => {
        loading.close()
      }, 1000)
    })
  } else if (type === PayType.BALANCEPAY) {
    // 余额部分
    const total = userLevels.value[curIndex.value].needAmount
    if (total > parseFloat(currentBalance.value)) {
      ElMessage({
        message: $t('myBalance.balanceInsufficient') + currentBalance.value,
        type: 'warning',
        duration: 3000
      })
      return
    }
    closePop()
    ElMessageBox.confirm($t('myBalance.payTips'), $t('tips'), {
      distinguishCancelAndClose: true,
      confirmButtonText: $t('determine'),
      cancelButtonText: $t('cancel')
    }).then(() => {
      http.post('/p/level/payLevel', {
        id: memberLevelId,
        payType: type,
        validateType: paySettlementType.value === 1 ? 2 : undefined, // 通联支付需要传2 (验证类型 0:无验证, 1:短信验证码, 2：支付密码)
        systemType: paySettlementType.value === 1 ? 2 : undefined // 通联支付需要传2 (系统类型 1:移动端 2:pc)
      }).then(({ data }) => {
        if (paySettlementType.value === 1) {
          const allinpayData = {
            bizOrderNo: data.bizOrderNo,
            jumpUrl: window.location.origin + '/member-center',
            errorJumpUrl: window.location.origin + '/member-center',
            jumpPageType: 1
          }
          http.post('/p/allinpay/order/payConfirmByFrontPwd', allinpayData).then(({ data }) => {
            nextTick(() => {
              location.href = data
            })
          })
          return
        }
        if (data.type === 1) {
          ElMessage({
            message: $t('payment.paymentSuccessful'),
            type: 'success',
            duration: 1000,
            onClose () {
              router.push({ path: '/member-center' })
            }
          })
        } else {
          ElMessage({
            message: data.message,
            type: 'error',
            duration: 1000
          })
        }
      })
    })
  }
}

// 关闭弹窗
const closePop = () => {
  isShowPop.value = false
  isPayPop.value = false
  isWxPop.value = false
  isAllinpayPop.value = false
}

// 点击完成支付
const paySuccess = () => {
  http.get('/p/level/isPay', {
  }).then(({ data }) => {
    if (data === 1) {
      ElMessage({
        message: $t('memberCenter.purchaseSuccess'),
        type: 'success',
        duration: 1500
      })
    } else {
      ElMessage({
        message: $t('memberCenter.purchaseFailure'),
        type: 'error',
        duration: 1500
      })
    }
  })
  isShowPop.value = false
  isPayPop.value = false
  isWxPop.value = false
  router.push({
    path: '/member-center'
  })
}
const getVipInternationalization = (data) => {
  if (!data) return
  const lang = Cookie.get('bbcLanguage') || 'zh_CN'
  data.forEach(element => {
    let levelNameCn, levelNameEn
    if (!element.userLevelLangList) return
    element.userLevelLangList.forEach(val => {
      if (val.lang === 0) {
        levelNameCn = val.levelName
      }
      if (val.lang === 1) {
        levelNameEn = val.levelName
      }
    })
    element.levelName = lang === 'zh_CN' ? levelNameCn : levelNameEn || levelNameCn
  })
}

// 获取是否完成实名/绑定手机号提示
const getTip = (type) => {
  if (type === PayType.BALANCEPAY) {
    // 余额支付查询是否实名认证
    let msg = ''
    if (!allinpayMemberInfo) {
      ElMessage({
        message: $t('allinpay.loadingTip'),
        type: 'error',
        duration: 1000
      })
    }
    if (!allinpayMemberInfo.allinpayRealNameSet) {
      msg += $t('allinpay.realNameTip1')
    }
    if (!allinpayMemberInfo.allinpayPhoneBind) {
      if (msg) {
        msg += $t('allinpay.bindPhone3')
      } else {
        msg += $t('allinpay.bindPhone')
      }
    }
    if (!allinpayMemberInfo.allinpayPayPwdSet) {
      if (msg) {
        msg += $t('allinpay.setPayPwd2')
      } else {
        msg += $t('allinpay.setPayPwd')
      }
    }
    if (msg) {
      ElMessage({
        message: $t('allinpay.tip1') + msg + $t('allinpay.tip2'),
        type: 'error',
        duration: 1000
      })
      return true
    }
  }
  if (type === PayType.WECHATPAY_SWEEP_CODE || type === PayType.ALIPAY) {
    if (!allinpayMemberInfo) {
      ElMessage({
        message: $t('allinpay.loadingTip'),
        type: 'error',
        duration: 1000
      })
      return true
    }
    if (!allinpayMemberInfo.allinpayPayAcctBind && !allinpayMemberInfo.allinpayPhoneBind) {
      // 非无感注册且未绑定手机号的用户需要先绑定手机号
      ElMessage({
        message: $t('allinpay.tip3'),
        type: 'error',
        duration: 1000
      })
      return true
    }
  }
}

</script>

<style lang="scss" scoped>
@use '../index.scss' as index-mc;
@use './index.scss';
@use '../../payment/index.scss' as index-payment;
</style>
